import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useAntdTable } from 'ahooks';
import { Col, Form, Modal, Row, Table, Tag } from 'antd';
import { cloneDeep } from 'lodash-es';

import CanvasRecord from '@/components/canvasRecord';
import { PointVo, Status, drawMap, statusColor } from '@/components/canvasRecord/drawMap';
import Text from '@/components/text';

import { usePermission } from '@/auth';
import { proInspectionRecordListPoint } from '@/services/bizApi/shengchanxunjianjilujiekou';
import { Icon } from '@iconify/react/dist/iconify.js';

import EditModal, { EditRef } from './edit';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type DetailRef = {
  open: (
    arg: EditOpenBaseArgs & {
      id: string;
    }
  ) => void;
};

export type EditProps = {};

const Detail: React.ForwardRefRenderFunction<DetailRef, EditProps> = (_, ref) => {
  const permission = usePermission();
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<DetailRef['open']>[0]>();
  const [tableData, setTableData] = useState<PointVo[]>([]);
  const [isMobile, setIsMobile] = useState(false);
  const editRef = useRef<EditRef>(null);

  const table = useAntdTable(
    async () => {
      const res = await proInspectionRecordListPoint({
        id: args?.id
      });

      let dataSource: PointVo[] = [];
      dataSource = cloneDeep(res.data) as PointVo[];

      dataSource.forEach((item) => {
        if (item.status === 3 && item.normal === false) {
          item.status = Status.异常 as any;
        }
        const coordinate = drawMap.find((d) => d.name === item.pointName);
        if (coordinate) {
          item.x = (coordinate.x as number) || 0;
          item.y = coordinate.y || 0;
          item.name = item.pointName!;
        }
      });
      setTableData((dataSource as PointVo[]) || []);
      return {
        list: res.data?.filter((m) => m.status === Status.已巡检) || [],
        total: res.data?.length || 0,
        pagination: false
      };
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        onSearch();
        setArgs(arg);
        setOpen(true);
        //判断是否是移动端
        if (window.innerWidth < 1024) {
          setIsMobile(true);
        } else {
          setIsMobile(false);
        }
      }
    };
  });

  const onSearch = () => {
    table.search.submit();
  };

  const onCancel = () => {
    setOpen(false);
    args?.onSuccess?.();
  };

  const showDetail = (arg: PointVo, type: 'detail' | 'edit') => {
    let argData = {} as PointVo;
    if (type === 'edit') {
      const currentData = tableData.find((item) => item.pointName === arg.name)!;
      argData = { ...arg, ...currentData };
    } else {
      argData = arg;
    }

    editRef.current?.open({
      type: type,
      rowData: argData,
      onSuccess: () => {
        onSearch();
      }
    });
  };

  return (
    <Modal
      title="巡检进度详情"
      open={open}
      footer={null}
      onCancel={onCancel}
      width={isMobile ? '100%' : '80%'}
      centered={true}
    >
      <Row>
        <Col span={isMobile ? 24 : 16}>
          {/* 颜色描述 */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Icon
                icon="ri:checkbox-blank-circle-fill"
                fontSize={30}
                color={statusColor[Status.已巡检].rgba}
              />
              已巡检
            </div>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Icon
                icon="ri:checkbox-blank-circle-fill"
                fontSize={30}
                color={statusColor[Status.待巡检].rgba}
              />
              待巡检
            </div>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Icon
                icon="ri:checkbox-blank-circle-fill"
                fontSize={30}
                color={statusColor[Status.异常].rgba}
              />
              有异常
            </div>
          </div>
          <div style={{ padding: '20px', display: 'flex', justifyContent: 'center' }}>
            <CanvasRecord onClick={(event) => showDetail(event, 'edit')} dataSource={tableData} />
          </div>
          <div style={{ color: 'red', fontSize: '14px', textAlign: 'center' }}>
            点击图中点位上传巡检记录
          </div>
        </Col>
        <Col span={isMobile ? 24 : 8}>
          <Table
            size="small"
            columns={[
              {
                title: '巡检顺序',
                dataIndex: 'index',
                width: 100,
                align: 'center',
                key: 'index',
                render: (_, _record, index) => {
                  return index + 1;
                }
              },
              {
                title: '巡检点位',
                dataIndex: 'pointName',
                key: 'pointName'
              },
              {
                title: '巡检状态',
                dataIndex: 'status',
                key: 'status',
                render: (status, record) => {
                  if (status === 1) {
                    return <Tag color={statusColor[Status.待巡检].color}>待巡检</Tag>;
                  } else if (status === 3 && !record.normal) {
                    return <Tag color={statusColor[Status.异常].color}>异常</Tag>;
                  } else {
                    return <Tag color={statusColor[Status.已巡检].color}>已巡检</Tag>;
                  }
                }
              },
              {
                title: '操作',
                align: 'center',
                dataIndex: 'operation',
                key: 'operation',
                render: (_, record) => {
                  const detailsData = { ...record, name: record.pointName };
                  return (
                    <Text.Space>
                      {permission.check() && record.status != Status.待巡检 && (
                        <Text
                          type="primary"
                          onClick={() => showDetail(detailsData as PointVo, 'detail')}
                        >
                          详情
                        </Text>
                      )}
                    </Text.Space>
                  );
                }
              }
            ]}
            {...table.tableProps}
            pagination={false}
            rowKey="pointRecordId"
          />
        </Col>
      </Row>

      <EditModal ref={editRef} />
    </Modal>
  );
};

export default forwardRef(Detail);
